<?php


namespace Transparency\Resources;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\RequestOptions;
use Transparency\Errors\ResponseException;
use Transparency\Errors\TransparencyException;
use Transparency\Resource;


class Codes extends Resource
{
    protected $subversion = 'v1.2/serial';

    /**
     * @param string $gtin
     * @param int $count
     * @param string $lotNumber
     * @return string|array $res
     * @throws TransparencyException
     */
    public function requestCodes(string $gtin, int $count,string $lotNumber):string|array
    {
        if($count<=0)throw new TransparencyException("request Transparency Codes: Count should be greater than 0");
        $res=$this->call('POST', 'sgtin', [
            RequestOptions::JSON => [
                'gtin' => $gtin,
                'count' => $count,
                "ilmd"=>["lotNumber"=>$lotNumber]
            ]
        ]);
        if(!empty($this->headers['Location'][0])){
            preg_match('/job\/(.+)/', $this->headers['Location'][0], $matches);
            return $matches[1];
        }else{
            return $res;
        }
    }

    public function getJobStatus(string $job)
    {
        return $this->call('GET', 'job/'.$job);
    }
    public function getCodes(string $url)
    {
        try{
            $httpClient = new Client();
            $res=$httpClient->get($url);
            $data=$res?->getBody()?->getContents();
            return $data?json_decode($data,true):[];
        }catch (RequestException $e){
            $xml=$e->getResponse()->getBody()->getContents();
            if($xml){
                $msg=simplexml_load_string($xml);
                $msg=$msg->Message;
            }else{
                $msg=$e->getMessage();
            }
            throw new ResponseException($msg);
        }
    }
}
